<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/model/fields/Int.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/database/core/IAutoUpdateColumn.php';

class Featured extends Integer implements IAutoUpdateColumn
{	
	private $shouldAllowOnlyOne;
	private $withinGroup;
	
	public function __construct(IDatabaseRecord &$object, $shouldAllowOnlyOne = false, $withinGroup = false)
	{
		// previoulsy was using debug_backtrace()
		// but we found an issue when (we think) php was running as CGI.  The ['object']
		// key was not being passed.
		// signature was:
		// public function __construct($length = null, $defaultValue = null)
		// $this->model was being set via:
		// $tmp =  debug_backtrace();
		// $this->model        = &$tmp[1]['object'];
		
		$this->model              = $object;
		$this->field_type         = 'integer';
		$this->length             = 1;
		$this->shouldAllowOnlyOne = $shouldAllowOnlyOne;
		$this->withinGroup        = $withinGroup;
	}
	
	public function update()
	{
		global $config;
		
		if ($this->data['value'] == 1)
		{
			if ($this->shouldAllowOnlyOne)
			{
				if ($this->withinGroup):
					
					$column = $this->withinGroup;
					$value  = $this->model->$column->value;
					$query = "UPDATE ".strtolower(get_class($this->model))." SET ".$this->column."=0 WHERE ".$this->column."=1 AND ".$column." = ".$value;
				else:
					$query = "UPDATE ".strtolower(get_class($this->model))." SET ".$this->column."=0 WHERE ".$this->column."=1";
				endif;
					
				// the record system is using Transactions here.
				// so we don't have to set anythign to null.
				// now this is just for MySQL, this may have
				// to be changed for other DB systems
				
				$dbh =& Database::connection();
				$stmt = $dbh->prepare($query);
				$stmt->execute();
			}
		}
	}
}
?>
